package com.cari.oa.util;

import com.alibaba.fastjson.JSON;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * User: yexuhui
 * Date: 12-12-10
 * Time: 下午5:45
 */
public class Utils {

    /**
     * 生成UUID
     * @return uuid
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成正常的JSON RESPONSE
     * @return 无错的json串
     */
    public static String normalJsonResp() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 生成错误的json响应
     * @param error 错误描述
     * @return 错误的json串
     */
    public static String errorJsonResp(String error) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 0);
        resultMap.put("message", error);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 生成32位的MD5串
     * @param str 原始字符串
     * @return MD5后的字符串
     */
    public static String md5(String str) {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] bytes = str.getBytes();
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(bytes);
            byte[] updateBytes = messageDigest.digest();
            int len = updateBytes.length;
            char[] myChar = new char[len * 2];
            int k = 0;
            for (byte byte0 : updateBytes) {
                myChar[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
                myChar[(k++)] = hexDigits[(byte0 & 0xF)];
            }

            return new String(myChar);
        } catch (Exception e) {
            throw new RuntimeException(str + " : md5失败", e);
        }
    }
    
	/**
	 * 从http请求中获取真实的IP
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

    public static void main(String[] args) {
        Object str = null;
        String st2 = (String)str;
        System.out.println(st2);
    }
}
